import { RouteRecordRaw } from 'vue-router'
import { defineStore } from 'pinia'
import router from '@/router'
import { defaultRoutes } from '@/router/routes/default-routes'
import { constantRoutes } from '@/router/routes/constants'
import { doAsyncRoutes } from '@/setting'
import { getMenusByAppUser, getPermissionsByAppUser } from '@/api/user'
import { generatorRoutes, mapTwoLevelRouter, generatorPermissions } from '../help'

const usePermissionStore = defineStore('permission-route', {
  state: () => {
    return {
      permissionRoutes: [] as RouteRecordRaw[],
      // 按钮权限
      resourcePermission: [] as string[],
      // 角色列表
      roles: [] as string[],
    }
  },
  getters: {
    getPermissionSideBar(state) {
      return state.permissionRoutes.filter((it) => {
        return it.meta && !it.meta.hidden
      })
    },
    getPermissionSplitTabs(state) {
      return state.permissionRoutes.filter((it) => {
        return it.meta && !it.meta.hidden && it.children && it.children.length > 0
      })
    },
    getTopLevelTabs(state) {
      return state.permissionRoutes
        .filter((it) => {
          return it.meta && !it.meta.hidden && it.children && it.children.length > 0
        })
        .map((it) => {
          const obj = { ...it, items: it.children }
          delete obj.children
          return obj
        })
    },
    getRoleList(state) {
      return state.roles
    },
  },
  actions: {
    // 获取路由
    async getRoutes() {
      try {
        if (doAsyncRoutes) {
          // 资源权限
          const permissionsRes = await getPermissionsByAppUser()
          this.roles = permissionsRes.result.roleList
          this.resourcePermission = generatorPermissions(permissionsRes.result.resourceList)
          // const res =
          await getMenusByAppUser()
          const async_menu = generatorRoutes(this.resourcePermission)
          return async_menu
        } else {
          return defaultRoutes
        }
      } catch (error) {
        console.log(error, '路由加载失败了，请检查是否获取到菜单')
        return []
      }
    },
    // 初始化路由
    async initPermissionRoute() {
      // 加载路由
      const accessRoutes = await this.getRoutes()
      const mapRoutes = mapTwoLevelRouter(accessRoutes)
      // 异步路由插入到route中
      mapRoutes.forEach((it: any) => {
        router.addRoute(it)
      })
      // 这个路由一定要放在最后
      router.addRoute({
        path: '/:pathMatch(.*)*',
        redirect: '/404',
        meta: {
          hidden: true,
        },
      })
      this.permissionRoutes = [...constantRoutes, ...accessRoutes]
    },
    isEmptyPermissionRoute() {
      return !this.permissionRoutes || this.permissionRoutes.length === 0
    },
    reset() {
      this.$reset()
    },
  },
})

export default usePermissionStore
